package com.zhongketech.sunflower.database;

import java.util.ArrayList;
import java.util.List;

import com.zhongketech.sunflower.IUpdateCallback;
import com.zhongketech.sunflower.MyApplication;
import com.zhongketech.sunflower.util.Constants;
import com.zhongketech.sunflower.util.Utilities;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * 数据保存
 * @author 905904
 *
 */
public class Data {

	private final static String TAG = "Data";

	public static final String DATATYPE_STOPAPP = "stopApp";
	public static final String DATATYPE_PHONEBLACKLIST = "phoneBlackList";
	public static final String DATATYPE_PHONEWHITELIST = "phoneWhiteList";
	public static final String DATATYPE_NETBLACKLIST = "netBlackList";
	public static final String DATATYPE_NETWHITELIST = "netWhiteList";


	/**
	 * 数据库相关
	 */
	private static SQLiteDatabase dbWriter;// 获得数据库可写操作的对象
	private static SQLiteDatabase dbReader;// 获得数据库可写操作的对象
	private static MySQLiteOpenHelper mySqlite;// 声明继承自SQLiteOpenHelper类的

	//单例实例化
	private static Data instance = new Data();
	private IUpdateCallback callback = null;

	private Data()
	{
		mySqlite = new MySQLiteOpenHelper(MyApplication.getAppContext());
		//creat table
		dbWriter = mySqlite.getWritableDatabase();// 获得数据库可写操作权限
		dbReader = mySqlite.getReadableDatabase();// 获得数据库可读操作权限
		String[] tables = getSqlTable();
		for(int i = 0;i < tables.length;i++)
		{
			dbWriter.execSQL(tables[i]);
		}

		syncMySql();
	}

	public static Data getinstance()
	{
		return instance;
	}

	private List<ApplicationData> appStopList = new ArrayList<ApplicationData>();
	private List<PhoneNumberData> phoneBlackList = new ArrayList<PhoneNumberData>();


	private void syncMySql()
	{
		/**
		 * 待优化，根据table --- 数据类型 ，数据结构 --- 数据对象来动态同步
		 */
		Cursor cursor = dbReader.query(Data.DATATYPE_STOPAPP,new String[]{"packageName","appName"},null,null,null,null,null);  
		while (cursor.moveToNext()) {  
			String appName = cursor.getString(cursor.getColumnIndex("appName"));  
			String packageName = cursor.getString(cursor.getColumnIndex("packageName"));  
			ApplicationData app = new ApplicationData(packageName,appName);
			add(app,Data.DATATYPE_STOPAPP);
			Utilities.logCat(TAG,"appName->"+appName+"  packageName->"+packageName,Constants.LOG_INFO);  
		}

		cursor = dbReader.query(Data.DATATYPE_PHONEBLACKLIST,new String[]{"name","num"},null,null,null,null,null);  
		while (cursor.moveToNext()) {  
			String name = cursor.getString(cursor.getColumnIndex("name"));  
			String num = cursor.getString(cursor.getColumnIndex("num"));  
			PhoneNumberData phoneNum= new PhoneNumberData(num,name);
			add(phoneNum,Data.DATATYPE_PHONEBLACKLIST);
			Utilities.logCat(TAG,"name->"+name+"  num->"+num,Constants.LOG_INFO);  
		}
	}

	private String[] getSqlTable()
	{

		String[] tables = {"create table if not exists "+DATATYPE_PHONEBLACKLIST+"(name vachar,num vachar ,unique(name,num))",
				"create table if not exists "+DATATYPE_STOPAPP+"(packageName vachar,appName vachar ,unique(packageName,appName))",};

		return tables;
	}

	public boolean isExit(Object object)
	{
		if(null != object && object instanceof ApplicationData)
		{
			ApplicationData app = (ApplicationData) object;
			for(int i = 0;i < appStopList.size();i++)
			{
				if(Constants.ITEM_EXISTS == app.getStatus(appStopList.get(i)) || Constants.ITEM_UPDATE == app.getStatus(appStopList.get(i)))
				{
					Utilities.logCat(TAG, "This is exit:"+app, Constants.LOG_WARNING);
					return true;
				}

			}
		}
		else if(null != object && object instanceof PhoneNumberData)
		{
			PhoneNumberData num = (PhoneNumberData) object;
			for(int i = 0;i < phoneBlackList.size();i++)
			{
				if(Constants.ITEM_EXISTS == num.getStatus(phoneBlackList.get(i)) || Constants.ITEM_UPDATE == num.getStatus(phoneBlackList.get(i)))
				{
					Utilities.logCat(TAG, "This is exit:"+num, Constants.LOG_WARNING);
					return true;
				}

			}
		}

		return false;
	}

	public boolean add(Object object,String dataType)
	{
		if(Data.DATATYPE_STOPAPP.equals(dataType))
		{
			ApplicationData app = (ApplicationData) object;
			for(int i = 0;i < appStopList.size();i++)
			{
				if(!(Constants.ITEM_ADD == app.getStatus(appStopList.get(i))))
				{
					Utilities.logCat(TAG, "This is exit:"+app, Constants.LOG_WARNING);
					return false;
				}

			}
			appStopList.add(app);
			dbWriter.insert(Data.DATATYPE_STOPAPP,null,app.getContentValues());
			return true;
		}
		else if(Data.DATATYPE_PHONEBLACKLIST.equals(dataType))
		{
			PhoneNumberData num = (PhoneNumberData) object;
			for(int i = 0;i < phoneBlackList.size();i++)
			{
				if(!(Constants.ITEM_ADD == num.getStatus(phoneBlackList.get(i))))
				{
					Utilities.logCat(TAG, "This is exit:"+num, Constants.LOG_WARNING);
					return false;
				}

			}
			phoneBlackList.add(num);
			dbWriter.insert(Data.DATATYPE_PHONEBLACKLIST,null,num.getContentValues());
			return true;
		}

		if(null != callback)
		{
			callback.update();
		}

		return false;
	}


	public boolean del(int index, String dataType)
	{
		if(Data.DATATYPE_STOPAPP.equals(dataType))
		{

			if(index < appStopList.size())
			{
				ApplicationData app = appStopList.get(index);
				dbWriter.delete(DATATYPE_STOPAPP, "packageName=?", new String[]{app.getPackageName()});
				appStopList.remove(index);
				return true;
			}


			return false;
		}
		else if(Data.DATATYPE_PHONEBLACKLIST.equals(dataType))
		{


			if(index < phoneBlackList.size())
			{
				PhoneNumberData num = phoneBlackList.get(index);
				dbWriter.delete(DATATYPE_PHONEBLACKLIST, "num=?", new String[]{num.getNumber()});
				phoneBlackList.remove(index);
				return true;
			}

			return false;
		}

		if(null != callback)
		{
			callback.update();
		}

		return false;
	}


	public boolean del(Object object,String dataType)
	{
		if(Data.DATATYPE_STOPAPP.equals(dataType))
		{
			ApplicationData app = (ApplicationData) object;
			for(int i = 0;i < appStopList.size();i++)
			{
				if(Constants.ITEM_UPDATE == app.getStatus(appStopList.get(i)) || Constants.ITEM_EXISTS == app.getStatus(appStopList.get(i)))
				{
					dbWriter.delete(DATATYPE_STOPAPP, "packageName=?", new String[]{app.getPackageName()});
					appStopList.remove(app);
					return true;
				}

			}


			return false;
		}
		else if(Data.DATATYPE_PHONEBLACKLIST.equals(dataType))
		{
			PhoneNumberData num = (PhoneNumberData) object;
			for(int i = 0;i < phoneBlackList.size();i++)
			{
				if(Constants.ITEM_UPDATE == num.getStatus(phoneBlackList.get(i)) || Constants.ITEM_EXISTS == num.getStatus(phoneBlackList.get(i)))
				{
					dbWriter.delete(DATATYPE_PHONEBLACKLIST, "num=?", new String[]{num.getNumber()});
					phoneBlackList.remove(num);
					return true;
				}

			}

			return false;
		}

		if(null != callback)
		{
			callback.update();
		}

		return false;
	}

//	private int findApplicationIndex(ApplicationData app)
//	{
//		for(int i = 0;app != null && i < appStopList.size();i++)
//		{
//			//先判断包名再判断应用名字，两者有一个符合即可
//			if(null != app.getPackageName() && app.getPackageName().equals(appStopList.get(i).getPackageName()))
//			{
//				return i;
//			}
//			else if(null != app.getAppName() && app.getAppName().equals(appStopList.get(i).getAppName()))
//			{
//				return i;
//			}
//		}
//		return -1;
//	}
//
//	private int findPhoneNumberIndex(PhoneNumberData num)
//	{
//		for(int i = 0;num != null && i < phoneBlackList.size();i++)
//		{
//			//先判断号码再判断名字
//			//			//号码判断：大于等于7只需判断后面相等即可
//			//			if(null != num.getNumber() && num.getNumber().length() < 7 && num.getNumber().equals(phoneBlackList.get(i).getNumber()))
//			//			{
//			//				return i;
//			//			}
//			//			else if(null != num.getNumber() && num.getNumber().length() >= 7 && num.getNumber().endsWith(phoneBlackList.get(i).getNumber()))
//			//			{
//			//				return i;
//			//			}
//			if(num.getNumber().equals(phoneBlackList.get(i).getNumber()))
//			{
//				return i;
//			}
//			else if(null != num.getName() && num.getName().equals(phoneBlackList.get(i).getName()))
//			{
//				return i;
//			}
//		}
//		return -1;
//	}

	//	public boolean removeDataItem(Object object,String dataType)
	//	{
	//		boolean ret = false;
	//		int index = -1;
	//
	//		if(Data.DATATYPE_STOPAPP.equals(dataType))
	//		{
	//			ApplicationData app = (ApplicationData) object;
	//			index = findApplicationIndex(app);
	//			if(-1 != index)
	//			{	
	//				appStopList.remove(index);
	//			}
	//		}
	//		else if(Data.DATATYPE_PHONEBLACKLIST.equals(dataType))
	//		{
	//			PhoneNumberData num = (PhoneNumberData) object;
	//			index = findPhoneNumberIndex(num);
	//			if(-1 != index)
	//			{	
	//				phoneBlackList.remove(index);
	//			}
	//		}
	//
	//		if(null != callback)
	//		{
	//			callback.update();
	//		}
	//		return ret;
	//	}

	public int getDataCount(String dataType)
	{

		if(Data.DATATYPE_STOPAPP.equals(dataType))
		{
			return appStopList.size();
		}
		else if(Data.DATATYPE_PHONEBLACKLIST.equals(dataType))
		{
			return phoneBlackList.size();
		}

		return 0;
	}

	public Object getData(int index,String dataType)
	{

		if(Data.DATATYPE_STOPAPP.equals(dataType) && index < appStopList.size())
		{	
			return appStopList.get(index);
		}
		else if(Data.DATATYPE_PHONEBLACKLIST.equals(dataType) && index < phoneBlackList.size())
		{
			return phoneBlackList.get(index);
		}

		return null;
	}

}
